<template>
  <div class="data-governance-container">
    <el-card shadow="hover">
      <!-- 顶部操作栏：过滤、新增、批量删除 -->
      <div class="toolbar">
        <el-form :inline="true" :model="filters" @submit.prevent="fetchData">
          <el-form-item label="昵称过滤">
            <el-input v-model="filters.nick" placeholder="输入昵称关键字" clearable></el-input>
          </el-form-item>
          <el-form-item label="地点过滤">
             <el-input v-model="filters.location" placeholder="输入地点关键字" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          </el-form-item>
        </el-form>
        <div>
            <!-- <el-button type="primary" :icon="Plus" @click="randomInt">开启随机生成数据</el-button> -->
            <span style="margin-right: 20px">
                随机生成数据:
                <el-switch v-model="randomBool" />
            </span>
            
            <el-button type="primary" :icon="Plus" @click="handleAdd">新增数据</el-button>
            <el-button type="danger" :icon="Delete" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="CmId" label="用户ID" width="150" sortable />
        <el-table-column prop="Avatar" label="头像" width="80">
           <template #default="scope">
             <el-avatar size="small" :src="scope.row.Avatar" />
             <!-- 或者 <img :src="scope.row.Avatar" style="width: 40px; height: 40px; border-radius: 50%;" /> -->
           </template>
        </el-table-column>
        <el-table-column prop="Nick" label="昵称" width="150" sortable />
        <el-table-column prop="Content" label="内容">
            <template #default="scope">
                <!-- 内容可能很长，考虑使用 tooltip 或限制高度 -->
                <el-tooltip effect="dark" :content="scope.row.Content" placement="top">
                    <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 300px;">
                        {{ scope.row.Content }}
                    </div>
                </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="Location" label="地点" width="120" />
        <el-table-column prop="PubTime" label="发布时间" width="180" sortable>
           <template #default="scope">
             {{ formatDateTime(scope.row.PubTime) }}
           </template>
        </el-table-column>
         <el-table-column prop="PraiseNum" label="点赞数" width="100" sortable />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-popconfirm
              title="确定删除这条数据吗?"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button size="small" type="danger" :icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- ... 分页组件保持不变 ... -->
       <el-pagination
        style="margin-top: 20px;"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑 对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"  
      :before-close="handleCloseDialog"
      draggable
    >
      <el-form :model="formData" :rules="formRules" ref="dataFormRef" label-width="80px">
        <el-form-item label="用户ID" prop="CmId">
          <el-input v-model="formData.CmId" placeholder="请输入用户ID"></el-input>
        </el-form-item>
        <el-form-item label="头像URL" prop="Avatar">
          <el-input v-model="formData.Avatar" placeholder="请输入头像URL"></el-input>
          <!-- 如果需要上传功能，这里需要替换为上传组件 -->
        </el-form-item>
        <el-form-item label="昵称" prop="Nick">
          <el-input v-model="formData.Nick" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="Content">
          <el-input
            type="textarea"
            :rows="4"
            v-model="formData.Content"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="地点" prop="Location">
          <el-input v-model="formData.Location" placeholder="请输入地点"></el-input>
        </el-form-item>
        <el-form-item label="点赞数" prop="PraiseNum">
           <el-input-number v-model="formData.PraiseNum" :min="0" controls-position="right" />
        </el-form-item>
        <!-- PubTime 通常由数据库自动管理，不在表单中编辑 -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios'; // 假设你使用 axios 进行 API 请求
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue';

// --- 响应式状态 ---
const tableData = ref([]); // 表格数据
const loading = ref(false); // 加载状态
const selectedRows = ref([]); // 表格中选中的行
const dialogVisible = ref(false); // 对话框可见性
const dialogTitle = ref(''); // 对话框标题
const isEditMode = ref(false); // 是否为编辑模式
const dataFormRef = ref(null); // 表单引用
const randomBool = ref(false); // 随机生成数据开关

// 过滤条件 (更新)
const filters = reactive({
  nick: '',
  location: '',
});

// 分页配置 (保持不变)
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 表单数据模型 (更新)
const initialFormData = {
  id: null,
  CmId: '',
  Avatar: '',
  Nick: '',
  Content: '',
  Location: '',
  // PubTime 通常不由前端设置
  PraiseNum: 0,
};
const formData = ref({ ...initialFormData });

// 表单验证规则 (更新)
const formRules = reactive({
  CmId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  Nick: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  Content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  // Avatar, Location, PraiseNum 可以根据需要添加验证规则
});

// --- 方法 ---

// 获取数据列表 (更新 API 参数)
const fetchData = async () => {
  loading.value = true;
  try {
    // **注意：请将 '/api/data/list' 替换为你实际的后端 API 地址**
    const response = await axios.get('/api/data/list', { // 确认后端 API 地址
      params: {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        nick: filters.nick || undefined, // 更新过滤参数
        location: filters.location || undefined, // 更新过滤参数
      },
    });
    if (response.data.code === 200) { // 假设后端返回 code 和 data
      tableData.value = response.data.data.items; // 确认后端数据结构
      pagination.total = response.data.data.total; // 确认后端数据结构
    } else {
      ElMessage.error(response.data.msg || '获取数据失败');
    }
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error('网络错误或服务器异常');
  } finally {
    loading.value = false;
  }
};

// 处理搜索 (保持不变)
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchData();
};

// 处理分页大小改变 (保持不变)
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  fetchData();
};

// 处理当前页改变 (保持不变)
const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage;
  fetchData();
};

// 处理表格行选中变化 (保持不变)
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 打开新增对话框 (更新表单重置)
const handleAdd = () => {
  isEditMode.value = false;
  dialogTitle.value = '新增数据';
  formData.value = { ...initialFormData }; // 使用更新后的 initialFormData
  dialogVisible.value = true;
  dataFormRef.value?.clearValidate();
};

// 打开编辑对话框 (保持不变，但 formData 结构已更新)
const handleEdit = (row) => {
  isEditMode.value = true;
  dialogTitle.value = '编辑数据';
  formData.value = { ...row };
  dialogVisible.value = true;
  dataFormRef.value?.clearValidate();
};

// 处理删除单行数据 (确认 API 地址)
const handleDelete = async (id) => {
  try {
    // **注意：请将 '/api/data/delete' 替换为你实际的后端 API 地址**
    const response = await axios.delete(`/api/data/delete/${id}`); // 确认后端 API 地址
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      fetchData();
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error('网络错误或服务器异常');
  }
};

// 处理批量删除 (确认 API 地址和参数)
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的数据');
    return;
  }
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条数据吗?`,
    '提示',
    { /* ... */ }
  ).then(async () => {
    const ids = selectedRows.value.map(row => row.id);
    try {
      // **注意：请将 '/api/data/batch-delete' 替换为你实际的后端 API 地址**
      const response = await axios.post('/api/data/batch-delete', { ids }); // 确认后端 API 地址和参数
      if (response.data.code === 200) {
        ElMessage.success('批量删除成功');
        fetchData();
      } else {
        ElMessage.error(response.data.msg || '批量删除失败');
      }
    } catch (error) {
      console.error("批量删除失败:", error);
      ElMessage.error('网络错误或服务器异常');
    }
  }).catch(() => { /* ... */ });
};

// 关闭对话框 (保持不变)
const handleCloseDialog = () => {
  dialogVisible.value = false;
  dataFormRef.value?.resetFields();
};

// 提交表单 (确认 API 地址和数据结构)
const handleSubmit = async () => {
  if (!dataFormRef.value) return;
  await dataFormRef.value.validate(async (valid) => {
    if (valid) {
      // **确认 API 地址**
      const apiUrl = isEditMode.value
        ? `/api/data/update` // 编辑 API
        : '/api/data/add'; // 新增 API
      const method = isEditMode.value ? 'put' : 'post';

      try {
        // **确认发送的数据结构 (formData.value)**
        const response = await axios({
          method: method,
          url: apiUrl,
          data: formData.value, // 确认后端需要的数据字段
        });

        if (response.data.code === 200) {
          ElMessage.success(isEditMode.value ? '更新成功' : '新增成功');
          handleCloseDialog();
          fetchData();
        } else {
          ElMessage.error(response.data.msg || (isEditMode.value ? '更新失败' : '新增失败'));
        }
      } catch (error) {
        console.error("提交失败:", error);
        ElMessage.error('网络错误或服务器异常');
      }
    } else {
      console.log('表单验证失败!');
      return false;
    }
  });
};

// 格式化日期时间 (保持不变)
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '';
  try {
    const date = new Date(dateTimeString);
    return date.toLocaleString();
  } catch (e) {
    return dateTimeString;
  }
};


// --- 生命周期钩子 ---
onMounted(() => {
  fetchData();
});

</script>

<style scoped>
/* .data-governance-container {
  padding: 20px;
} */

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: flex-start; /* 让表单和按钮顶部对齐 */
  margin-bottom: 15px;
  flex-wrap: wrap; /* 允许换行 */
}

.toolbar .el-form--inline .el-form-item {
  margin-bottom: 10px; /* 调整表单项间距 */
}

/* 修复 Popconfirm 和 Button 之间的间距 */
.el-table-column .el-button + .el-popconfirm {
  margin-left: 8px;
}
/* 或者统一设置按钮间距 */
.el-table-column .el-button + .el-button {
    margin-left: 8px;
}
.el-table-column .el-button + .el-popconfirm + .el-button {
    margin-left: 8px;
}


</style>